import java.util.*;

/**
 * 数组中紧跟key之后出现最频繁的数字
 *
 * @USER: Administrator
 * @DATE: 2024/10/5 上午11:14
 * @VERSION: 1.0.0
 */
public class LC2190 {
    public static void main(String[] args) {
        LC2190 lc2190 = new LC2190();
        System.out.println(lc2190.mostFrequent(new int[]{1,999,3,999,5,999,997,999,999,999},999));
    }

    public int mostFrequent(int[] nums, int key) {
        Map<Integer, Integer> map = new TreeMap<>();
        for (int i = 0; i < nums.length-1; i++) {
            if (nums[i] == key) {
                map.put(nums[i+1], map.getOrDefault(nums[i+1], 0) + 1);
            }
        }
        List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
        list.sort((o1, o2) -> -o1.getValue() + o2.getValue());
        return list.get(0).getKey();
    }

}
